<template>
	<view class="wrap">
		<u-navbar title-bold title-color="#fff" title="首页" :is-back="false" :background="background">
			<view class="slot-wrap" v-if="this.showIcon">
				<u-icon size="42" name="home" @click="navTo()"></u-icon>
			</view>
		</u-navbar>
		<Search @search-data="handleSearchData" v-show="false" />
		<scroll-view scroll-y="true">

			<view class="container">
				<view class="wrap-swiper">
					<u-swiper height="280" :list="swiperList" @click="goSwiperUrl(swiperList)"
						@change="changeSwiper"></u-swiper>
					<!-- <view class="head-text">常用服务</view> -->
					<u-grid :col="4" :border="false" class="common-grid">
						<u-grid-item v-for="(item,index) in commonList" :key="index" @click="goCommonView(item.url)">
							<u-icon :name="item.iconName" :size="84" color="#1890FF"></u-icon>
							<view class="grid-text">{{item.title}}</view>
						</u-grid-item>
					</u-grid>
				</view>
			</view>
			<hr class="divider">

			<view class="container">
				<view class="head-text">指标<span style="color:rgb(74, 134, 255)">统计</span></view>

				<view class="subsection">
					<view :class="['subsection1', { active: activeSection === 'section1' }]"
						@click="setActive('section1')">
						<view>进水</view>
					</view>
					<view :class="['subsection2', { active: activeSection === 'section2' }]"
						@click="setActive('section2')">
						<view>出水</view>
					</view>
				</view>


				<!-- <u-subsection :list="waterQualityHeadList" @change="sectionChange" :current="curNow"></u-subsection> -->
				<u-grid :col="4" :border="false" class="grid" v-if="curNow=='0'">
					<u-grid-item>
						<view class="grid-text">{{homeData.water_inflow_it_flow_rate}}<span>m³</span></view>
						<view class="grid-text">瞬时流量</view>
					</u-grid-item>
					<u-grid-item>
						<view class="grid-text">{{dayInflowAvg}}<span>m³</span></view>
						<view class="grid-text">本月日均流量</view>
					</u-grid-item>
					<u-grid-item>
						<view class="grid-text">{{dayInflow}}<span>m³</span></view>
						<view class="grid-text">今日累计流量</view>
					</u-grid-item>
					<u-grid-item>
						<view class="grid-text">{{monthInflow}}<span>m³</span></view>
						<view class="grid-text">本月累计流量</view>
					</u-grid-item>
				</u-grid>
			</view>
			<u-grid :col="4" :border="false" class="grid" v-if="curNow=='1'">
				<u-grid-item>
					<view class="grid-text">{{homeData.water_effluent_it_flow_rate}}<span>m³</span></view>
					<view class="grid-text">瞬时流量</view>
				</u-grid-item>
				<u-grid-item>
					<view class="grid-text">{{dayEffluentAvg}}<span>m³</span></view>
					<view class="grid-text">本月日均流量</view>
				</u-grid-item>
				<u-grid-item>
					<view class="grid-text">{{dayEffluent}}<span>m³</span></view>
					<view class="grid-text">今日累计流量</view>
				</u-grid-item>
				<u-grid-item>
					<view class="grid-text">{{monthEffluent}}<span>m³</span></view>
					<view class="grid-text">本月累计流量</view>
				</u-grid-item>
			</u-grid>


			<view class="head-text">水质监测</view>
			<u-subsection :list="waterQualityHeadList" @change="sectionChange2" :current="curNow2"></u-subsection>
			<u-grid :col="3" :border="false" class="grid">
				<u-grid-item v-for="(item,index) in waterWqList" :key="index">
					<view class="grid-text">{{item.title}}</view>
					<view class="grid-text">{{item.value}}<span>{{item.unit}}</span></view>
				</u-grid-item>
			</u-grid>

			<view class="head-text">今日报警响应率</view>
			<view class="charts-box">
				<qiun-data-charts type="ring" :opts="ringOpt" :chartData="ringData2" />
			</view>
			<view class="head-text">今日工单响应率</view>
			<view class="charts-box">
				<qiun-data-charts type="ring" :opts="ringOpt" :chartData="ringData1" />
			</view>

			<view class="head-text">设备运行状态</view>
			<view class="charts-box">
				<qiun-data-charts type="pie" :opts="opts" :chartData="chartData" />
			</view>
			<!-- <view class="head-text">设备在线状态</view>
				<view class="charts-box">
					<qiun-data-charts type="ring" :opts="ringOpt" :chartData="ringData" />
				</view> -->


		</scroll-view>
	</view>
</template>
<script>
	import Search from '@/components/headsearch/search.vue'
	import config from '@/common/config.js';

	export default {
		components: {
			Search
		},
		computed: {
			dayInflow() {
				if (this.homeData.water_day_inflow_count > 10000) {
					return (this.homeData.water_day_inflow_count / 10000).toFixed(2) + '万';
				} else {
					return this.homeData.water_day_inflow_count;
				}
			},
			monthInflow() {
				if (this.homeData.water_month_inflow_count > 10000) {
					return (this.homeData.water_month_inflow_count / 10000).toFixed(2) + '万';
				} else {
					return this.homeData.water_month_inflow_count;
				}
			},
			dayEffluent() {
				if (this.homeData.water_day_effluent_count > 10000) {
					return (this.homeData.water_day_effluent_count / 10000).toFixed(2) + '万';
				} else {
					return this.homeData.water_day_effluent_count;
				}
			},
			monthEffluent() {
				if (this.homeData.water_month_effluent_count > 10000) {
					return (this.homeData.water_month_effluent_count / 10000).toFixed(2) + '万';
				} else {
					return this.homeData.water_month_effluent_count;
				}
			},
			monthEffluent() {
				if (this.homeData.water_month_effluent_count > 10000) {
					return (this.homeData.water_month_effluent_count / 10000).toFixed(2) + '万';
				} else {
					return this.homeData.water_month_effluent_count;
				}
			},
			dayEffluentAvg() {
				if (this.homeData.water_day_effluent_avg > 10000) {
					return (this.homeData.water_day_effluent_avg / 10000).toFixed(2) + '万';
				} else {
					return this.homeData.water_day_effluent_avg;
				}
			},
			dayInflowAvg() {
				if (this.homeData.water_day_inflow_avg > 10000) {
					return (this.homeData.water_day_inflow_avg / 10000).toFixed(2) + '万';
				} else {
					return this.homeData.water_day_inflow_avg;
				}
			},
		},
		data() {
			return {
				activeSection: null,
				background: {
					backgroundColor: 'rgb(15, 110, 255)'
				},
				waterQualityHeadList: [{
					name: '进水'
				}, {
					name: '出水'
				}],
				curNow: 0,
				curNow2: 0,
				commonList: [{
						url: "/pages/sys/msg/liveVideo",
						iconName: 'play-circle',
						title: '视频监控',
					},
					{
						url: "/pages/sys/news/new-list",
						iconName: 'more-circle',
						title: '新闻公告',
					},
					{
						url: "/pages/sys/home/index",
						iconName: 'warning',
						title: '报警中心',
					},
					{
						url: "/pages/sys/eventwororder/adddeclaration/adddeclaration",
						iconName: 'order',
						title: '事件申报',
					}
				],
				swiperIndex: 0,
				swiperList: [],
				showIcon: true,
				homeData: {
					water_day_inflow_count: "1436.9",
					water_month_inflow_count: "1436.9",
					water_day_effluent_count: "10",
					water_month_effluent_count: "10",
					load_rate: "0",
					water_consumption: "0",
					water_inflow_it_flow_rate: "1436.9",
					water_effluent_it_flow_rate: "10",
					water_day_inflow_avg: "1436.9",
					water_day_effluent_avg: "10",
				},
				//厂站
				searchData: '', // 用于保存接收到的数据
				//进水水质
				waterWqList: [],
				inflowWater: [{
						title: 'COD',
						value: '4.32',
						unit: "mg/L"
					},
					{
						title: 'COD',
						value: '4.32',
						unit: "mg/L"
					},
					{
						title: 'COD',
						value: '4.32',
						unit: "mg/L"
					},
					{
						title: 'COD',
						value: '4.32',
						unit: "mg/L"
					},
				],
				//出水水质
				outWater: [{
						title: 'BOD',
						value: '4.32',
						unit: "mg/L"
					},
					{
						title: 'BOD',
						value: '4.32',
						unit: "mg/L"
					},
					{
						title: 'BOD',
						value: '4.32',
						unit: "mg/L"
					},
				],
				//pieEcharts
				chartData: {},
				opts: {
					color: ["#EE6666", "#73C0DE", "#91CB74", "#FAC858", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [5, 5, 5, 5],
					enableScroll: false,
					extra: {
						pie: {
							activeOpacity: 0.5,
							activeRadius: 10,
							offsetAngle: 0,
							labelWidth: 15,
							border: true,
							borderWidth: 3,
							borderColor: "#FFFFFF",
							linearType: "custom"
						}
					},
					timer: null
				},
				//ringEcharts
				ringData: {},
				ringData1: {},
				ringData2: {},
				ringOpt: {
					color: ["#EE6666", "#1890FF", "#91CB74", "#FAC858", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [5, 5, 5, 5],
					enableScroll: false,
					extra: {
						pie: {
							activeOpacity: 0.5,
							activeRadius: 10,
							offsetAngle: 0,
							labelWidth: 15,
							border: true,
							borderWidth: 3,
							borderColor: "#FFFFFF",
							linearType: "custom"
						}
					}
				}

			}

		},
		onLoad() {
			console.log('页面加载');
		},
		onShow() {
			this.getNewsBanner()
			this.startTimer()
			// uni.showLoading();
			console.log('页面显示');
		},
		onHide() {
			console.log('页面隐藏');
			this.stopTimer();
			// uni.hideLoading(); // 添加这行代码来隐藏加载状态
		},
		onUnload() {
			console.log('页面隐藏');
			this.stopTimer();
		},
		beforeDestroy() {
			console.log('页面隐藏');
			this.stopTimer();
		},

		methods: {
			setActive(section) {
				this.activeSection = section;
			},
			sectionChange(index) {
				this.curNow = index;
			},
			sectionChange2(index) {
				this.curNow2 = index;
				if (this.curNow2 == '0') {
					this.waterWqList = this.inflowWater
				} else {
					this.waterWqList = this.outWater
				}
			},
			navTo(url) {
				uni.reLaunch({
					url: "/pages/sys/msg/navigavtion"
				});
				uni.removeStorageSync('navId');
			},

			goSwiperUrl(list) {
				let url = list[this.swiperIndex].url
				let id = list[this.swiperIndex].id
				uni.navigateTo({
					url: `${url}?id=${id}`
				})
			},
			changeSwiper(e) {
				this.swiperIndex = e
			},

			goCommonView(url) {
				if (url.includes("/pages/sys/book/index")) {
					uni.switchTab({
						url: url
					})
				} else {
					uni.navigateTo({
						url: url
					})
				}
			},

			handleSearchData(data) {
				this.searchData = data; // 接收到子组件传递过来的数据
				this.getKeyWater()
				//进水
				this.getInflowWater()
				//出水
				this.getOutWater()
				//图表
				this.getServerData();
				this.getThingsData();
				this.getAlarmData();

				const tabBar = uni.getStorageSync('tabBar');
				if (tabBar == 0) {
					this.showIcon = false;
				}
			},

			startTimer() {
				this.timer = setInterval(async () => {
					try {
						// 执行异步任务并等待完成
						await this.getKeyWater();
						await this.getInflowWater();
						await this.getOutWater();
						await this.getServerData();
						await this.getThingsData();
						await this.getAlarmData();
						// await this.getWorkOrder(); // 如果需要，可以取消注释并使用
					} catch (error) {
						console.error('Error occurred during timer execution:', error);
					}
				}, 8000);
			},
			stopTimer() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
			},

			getNewsBanner() {
				this.$u.api.news({
					"algorithmProcessId": "water_news_recommend",
					"param": {
						"data": {

						}
					}
				}).then(res => {
					this.swiperList = res.data.data.result.map(item => {
						return {
							id: item.id,
							image: config.adminPath + item.news_coverphoto,
							url: '/pages/sys/news/new-detail'
						};
					})
				})
			},

			getInflowWater() {
				this.$u.api.inflowWater({
					"algorithmProcessId": "waterInflowReadData",
					"param": {
						"data": {
							structure_uuid: uni.getStorageSync('navId')
						}
					}
				}).then(res => {
					this.inflowWater = res.data.data.result.tags.map(item => {
						return {
							title: item.tagDescribe,
							value: item.value,
							unit: item.unit
						}
					})
					this.sectionChange2(this.curNow2);
				})
			},
			getOutWater() {
				this.$u.api.outWater({
					"algorithmProcessId": "waterEffluentReadData",
					"param": {
						"data": {
							structure_uuid: uni.getStorageSync('navId')
						}
					}
				}).then(res => {
					this.outWater = res.data.data.result.tags.map(item => {
						return {
							title: item.tagDescribe,
							value: item.value,
							unit: item.unit
						}
					})
					this.sectionChange2(this.curNow2);
				})
			},

			getServerData() {
				this.$u.api.eqStateData({
					"algorithmProcessId": "equipment_status_network_status",
					"param": {
						"data": {
							structure_uuid: uni.getStorageSync('navId')
						}
					}
				}).then(response => {
					let chartData = response.data.data.result.statusResult.map(item => {
						let statusMap = {
							'1': '异常',
							'2': '运行',
							'3': '停止',
							'4': '维修维护'
						};
						return {
							name: statusMap[item.status],
							value: item.status_count
						};
					});

					setTimeout(() => {
						//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
						let res = {
							series: [{
								data: chartData
							}]
						};
						this.chartData = JSON.parse(JSON.stringify(res));
					}, 500);

				})

			},

			getThingsData() {
				this.$u.api.getThingsResponse({
					"algorithmProcessId": "getThingsResponse",
					"param": {
						"data": {

						}
					}
				}).then(response => {
					let okOrder = response.data.data.result.okOrder;
					let noOrder = response.data.data.result.noOrder;

					let ringData1 = [{
						"name": "已响应",
						"value": okOrder
					}, {
						"name": "未响应",
						"value": noOrder
					}];
					setTimeout(() => {
						//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
						let res1 = {
							series: [{
								data: ringData1
							}]
						};
						this.ringData1 = JSON.parse(JSON.stringify(res1));
					}, 500);
				})
			},

			getAlarmData() {
				this.$u.api.getStationAlarmData({
					"algorithmProcessId": "getStationAlarmData",
					"param": {
						"data": {

						}
					}
				}).then(response => {
					let ringData2 = response.data.data.result.map(item => {
						return {
							name: item.type,
							value: item.value
						};
					})
					setTimeout(() => {
						//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
						let res2 = {
							series: [{
								data: ringData2
							}]
						};
						this.ringData2 = JSON.parse(JSON.stringify(res2));
					}, 500);
				})

			},
			//关键指标
			getKeyWater() {
				this.$u.api.searchKey({
					"algorithmProcessId": "getStationHomeData",
					"param": {
						"data": {
							structure_uuid: uni.getStorageSync('navId')
						}
					}
				}).then(res => {
					if (res && res.data.data.result.home_data) {
						this.homeData = res.data.data.result.home_data
					}
				})
			},


		}
	};
</script>
<style lang="scss">
	@import '../../../common/uni.css';

	page {
		background-color: #f5f5f5;
	}

	.container {
		padding: 0 28rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);

		.head-text {
			font-size: 32rpx;
			font-weight: bold;
			color: #333333;
			padding: 12rpx 0;
			margin-bottom: 24rpx;
		}

	}

	.wrap-swiper {
		padding-top: 24rpx;
	}

	.subsection {
		display: flex;
		padding: 0 84rpx;
		justify-content:space-between;
	}

	.subsection1,
	.subsection2 {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 240rpx;
		line-height: 64rpx;
		border-radius: 50rpx;
		transition: background-color 0.3s;
		background-color: rgb(218, 223, 231);
		color:#333;
		margin-left:48rpx；
	}

	.subsection1.active,
	.subsection2.active {
		background-color: rgb(72, 137, 252);
		color:#fff;
	}
	

	.common-grid {
		background-color: #fff;
		padding: 34rpx 0 0;

		.grid-text {
			font-size: 24rpx;
			margin-top: 12rpx;
			color: rgb(67, 83, 108);
			font-weight: bold;
		}
	}

	.grid {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 18rpx;

		.grid-text {
			font-size: 24rpx;
			margin-top: 28rpx;
			color: rgb(67, 83, 108);
			font-weight: bold;
		}

	}

	.charts-box {
		width: 100%;
		height: 600rpx;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 24rpx;
	}

	.panel {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		grid-gap: 20rpx;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 24rpx;

	}

	.item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 2rpx solid #ccc;
		padding: 16rpx 0;
	}

	.label {
		font-size: 28rpx;
		color: $u-type-info;
		font-weight: bold;
		width: 40%;
	}

	.value {
		font-size: 28rpx;
		color: #666;
		font-weight: bold;
	}

	.unit {
		color: $u-type-info;
		font-size: 32rpx;
		margin-left: 8rpx;
	}

	.u-title {
		font-weight: bold !important;
	}

	.slot-wrap {
		margin-left: 18rpx;
	}

	.divider {
		border: 0;
		height: 20rpx;
		background-color: #f5f5f5;
		/* 修改为你需要的颜色 */
		// margin: 10px 0; /* 调整上下间距 */
	}
</style>